package org.example.maven.museumuser.config;

import org.example.maven.museumuser.interceptors.JwtAuthenticationFilter;
import org.example.maven.museumuser.interceptors.MyAccessDeniedHandler;
import org.example.maven.museumuser.utils.PermitAllUrlProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;
import java.util.List;

@Configuration
@EnableMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfig {
    @Autowired
    private JwtAuthenticationFilter jwtAuthenticationFilter;
    @Autowired
    private MyAccessDeniedHandler myAccessDeniedHandler;
    /**
     * 允许匿名访问的地址
     */
    @Autowired
    private PermitAllUrlProperties permitAllUrl;
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        System.out.println("SecurityConfig.securityFilterChain()");
        System.out.println("Permitted URLs: " + permitAllUrl.getUrls()); // 调试输出
        // 注解标记允许匿名访问的url
        http
                .cors(cors -> cors.configurationSource(corsConfigurationSource())) // ✅ 启用 CORS
                .csrf(AbstractHttpConfigurer::disable)
                // 关键：注册异常处理器
                .exceptionHandling(exception -> exception
                        .accessDeniedHandler( myAccessDeniedHandler) // 处理 403
                )

                // 权限配置
                .authorizeHttpRequests(auth -> {
                    // 配置匿名访问URL
                    auth.requestMatchers(
                            permitAllUrl.getUrls().toArray(new String[0])
                    ).permitAll();
                    auth
                            .requestMatchers(HttpMethod.OPTIONS, "/**").permitAll() // ✅ 放行 OPTIONS
                            .requestMatchers("/exhibition/**").permitAll()
                            .requestMatchers("/getCode/**").permitAll()
                            .requestMatchers("/user/register").permitAll()
                            .requestMatchers("/user/login").permitAll()
                            .anyRequest().authenticated(); // 其他接口需要认证
                })
                // 使用自定义的JWT过滤器
                .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);

        return http.build();
    }

    // 创建与 WebConfig 一致的 CORS 配置源
    private CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowedOrigins(Arrays.asList(
                "http://localhost:5173",
                "http://localhost:3000",
                "http://localhost:8070",
                "http://localhost:80",
                "http://121.40.32.236:8070"
        ));
        config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"));
        config.setAllowedHeaders(List.of("*"));
        config.setAllowCredentials(true);
        config.setMaxAge(3600L);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        return source;
    }

    // 关键：暴露 AuthenticationManager
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authConfig) throws Exception {
        return authConfig.getAuthenticationManager();
    }

    // 密码加密器
    @Bean
    public PasswordEncoder passwordEncoder() {
        return  NoOpPasswordEncoder.getInstance();
    }
}
